<?php
/**
 * User: ngreduce
 * Date: 11.03.11
 * Time: 16:47
 */

class MailNotificationHelper {

    /*
     * Send registration email
     * $options = array(':name'=>'value')
     */
    public static function userRegistrationCompleted($email, $options)
    {
        $subject = Yii::t('mail', 'Registration completed');
        $content = self::_renderTemplate('registration_completed', $options);
        return self::sendMail($email, $subject, $content);
    }

    public static function userNewJobRequest($email, $options)
    {
        $subject = Yii::t('mail', 'New request for "{job}"', array('{job}'=>$options['job']->title));
        $content = self::_renderTemplate('job_new_request', $options);
        return self::sendMail($email, $subject, $content);
    }

    public static function userItemRejected($email, $options)
    {
        $subject = Yii::t('mail', '"{title}" has bin rejected', array('{title}'=>$options['model']->title));
        $content = self::_renderTemplate('item_rejected', $options);
        return self::sendMail($email, $subject, $content);
    }

    /******** Admin notifications **********/
    public static function adminPengingItem($model)
    {
        $adminEmail = Yii::app()->params['adminEmail'];
        $lang = Yii::app()->params['defaultLang'];
        $subject = Yii::t('mail', 'New pending item', null, null, $lang);
        $content = self::_renderTemplate('admin_pending_item', array('model'=>$model), $lang);
        return self::sendMail($adminEmail, $subject, $content);
    }

    /*
     * Send mail
     * @return bool
     */
    public static function sendMail($email,$subject,$message) {
    	$adminEmail = Yii::app()->params['adminEmail'];
	    $headers = "MIME-Version: 1.0\r\nFrom: $adminEmail\r\nReply-To: $adminEmail\r\nContent-Type: text/html; charset=utf-8";
	    $message = wordwrap($message, 70);
	    $message = str_replace("\n.", "\n..", $message);
	    return mail($email,'=?UTF-8?B?'.base64_encode($subject).'?=',$message,$headers);
	}

    /*
     * Renders a template with a placeholders
     * @return string result
     */
    protected static function _renderTemplate($template, $options=null, $language = null)
    {
        $fileName = Yii::getPathOfAlias('application.data.email_templates').'/'.$template.'.php';
        $fileName = Yii::app()->findLocalizedFile($fileName, null, $language);

        if (is_array($options))
            extract($options, EXTR_PREFIX_SAME, 'data');
        else
            $data = $options;
        ob_start();
        ob_implicit_flush(false);
        require($fileName);
        return ob_get_clean();
    }
}
 
